package elasticsearchDemo.demo;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonObject;
import com.sun.org.apache.bcel.internal.generic.NEW;
/**
 * Elasticsearch索引库的创建及数据添加
 * @author Shensg
 *
 * 2018年10月8日
 */
public class IndexCreateAndFillDataDemo {
private Logger logger = LoggerFactory.getLogger(Demo_1.class);
	
	public final static String host = "127.0.0.1";
	
	public final static int port = 9300;//http请求的端口是9200，客户端是9300
	
	private  TransportClient client;
	
	/*
	 * 建立链接
	 */
	@SuppressWarnings({ "resource", "unchecked" })
	
	public void getConnect() throws UnknownHostException {
		Settings settings = Settings.builder().put("cluster.name", "my-application").build();
		client = new PreBuiltTransportClient(settings)
				.addTransportAddress(new TransportAddress(InetAddress.getByName(host), port));
		logger.info("ElasticSearch connect info:"+client.toString());
	} 
	/**
	 * 關閉鏈接
	 */
	
	public void closeConnect() {
		if(client!=null) {
			client.close();
			logger.info("connect closed");
		}
	}
	/**
	 * 创建索引
	 * @throws IOException
	 */
	@Test
	public void addIndex() throws IOException {
		getConnect();
		IndexResponse response = client.prepareIndex( 
				"食物", "ssgsmall").setSource(XContentFactory.jsonBuilder()
				.startObject().field("userName","张三")
				.field("sendDate",new Date())
				.endObject()).get();
		logger.info("索引名称:" + response.getIndex() + "\n类型:" + response.getType()
        + "\n文档ID:" + response.getId() + "\n当前实例状态:" + response.status());
		closeConnect();
	}
	/**
	 * 向索引添加JSON数据
	 * @throws IOException
	 */
	@Test
	public void addIndexJson() throws IOException {
		String jsonStr = "{" +
				                 "\"userName\":\"张三\"," +
				                 "\"sendDate\":\"2017-11-30\"," +
				                "\"msg\":\"你好李四\"" +
			            "}";
		getConnect();
		IndexResponse response = client.prepareIndex( 
				"食物", "ssgsmall").setSource(jsonStr,XContentType.JSON).get();
		logger.info("索引名称:" + response.getIndex() + "\n类型:" + response.getType()
        + "\n文档ID:" + response.getId() + "\n当前实例状态:" + response.status());
		closeConnect();
	}
	
	/**
	 * 向索引添加Map数据
	 * @throws IOException
	 */
	@Test
	public void addIndexMap() throws IOException {
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("userName", "张三3");
        map.put("sendDate", new Date());
        map.put("msg", "你好李四4");
		getConnect();
		IndexResponse response = client.prepareIndex( 
				"食物", "ssgsmall").setSource(map).get();
		logger.info("索引名称:" + response.getIndex() + "\n类型:" + response.getType()
        + "\n文档ID:" + response.getId() + "\n当前实例状态:" + response.status());
		closeConnect();
	}
	
	/**
	 * 向索引添加JSONObject数据
	 * @throws IOException
	 */
	@Test
	public void addIndexJsonObject() throws IOException {
		JsonObject jsonObject = new JsonObject();
		jsonObject.addProperty("userName", "张三jsonObject");
		jsonObject.addProperty("sendDate", "2017-11-23");
		jsonObject.addProperty("msg","你好李四jsonObject");
		getConnect();
		IndexResponse response = client.prepareIndex( 
				"食物", "ssgsmall").setSource(jsonObject,XContentType.JSON).get();
		logger.info("索引名称:" + response.getIndex() + "\n类型:" + response.getType()
        + "\n文档ID:" + response.getId() + "\n当前实例状态:" + response.status());
		closeConnect();
	}
	
	/**
	 * 向索引获取data
	 * @throws IOException
	 */
	@Test
	public void getIndexData() throws IOException {
		getConnect();
		GetResponse  response = client.prepareGet("食物", "ssgsmall","DMivXWYBuNzJtBuGF1y9").get();
		logger.info("索引库的数据:" + response.getSourceAsString());
		closeConnect();
	}
	
	/**
	 * 向索引更新data
	 * @throws IOException
	 */
	@Test
	public void updateIndexData() throws IOException {
		getConnect();
		JsonObject jsonObject = new JsonObject();
        
        jsonObject.addProperty("userName", "王五");
        jsonObject.addProperty("sendDate", "2008-08-08");
        jsonObject.addProperty("msg","你好,张三，好久不见");
		UpdateResponse  updateResponse = client.prepareUpdate("食物", "ssgsmall","DMivXWYBuNzJtBuGF1y9").setDoc(jsonObject.toString(),XContentType.JSON).get();
		logger.info("updateResponse索引名称:" + updateResponse.getIndex() + "\n updateResponse类型:" + updateResponse.getType()
        + "\n updateResponse文档ID:" + updateResponse.getId() + "\n当前实例updateResponse状态:" + updateResponse.status());
		closeConnect();
	}
	
	/**
	 * 索引删除
	 * @throws IOException
	 */
	@Test
	public void deleteIndex() throws IOException {
		getConnect();
        DeleteResponse  response = client.prepareDelete("食物", "ssgsmall","DMivXWYBuNzJtBuGF1y9").get();
		logger.info("updateResponse索引名称:" + response.getIndex() + "\n updateResponse类型:" + response.getType()
        + "\n updateResponse文档ID:" + response.getId() + "\n当前实例updateResponse状态:" + response.status());
		closeConnect();
	}
	
}
